/*
 * @Description: 
 * @Version: 1.0
 * @Autor: ziwei
 * @Date: 2021-09-26 15:58:50
 * @LastEditors: ziwei
 * @LastEditTime: 2021-09-27 12:30:58
 */
import {forEachValue} from '../utils'
import Module from './module'

export default class ModuleCollection{
  constructor(rootModule){
    this.root = null;
    this.register(rootModule,[]);//root => a b a=>c
  }
  register(rawModule,path){
    const newModule = new Module(rawModule);
    //rawModule.newModule = newModule;//把新的模块 添加到原始对象上
    if(path.length == 0){
      this.root = newModule;
    }else{
      const parent = path.slice(0,-1).reduce((module,current)=>{
        return module.getChild(current);
      },this.root);
      parent.addChild(path[path.length-1],newModule);
    }

    if(rawModule.modules){
      forEachValue(rawModule.modules,(rawChildModule,key)=>{
        this.register(rawChildModule,path.concat(key))
      })
    }

    return newModule

    console.log(this.root);
  }

  getNamespaced(path){
    let module = this.root
    return path.reduce((namespacedStr,key)=>{
      module = module.getChild(key)
      return namespacedStr+(module.namespaced?key+"/":"")
    },'')
  }
}